﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace MapWindowDocking
{
    /// <summary>
    /// A xml reader for the favourites file.
    /// </summary>
    public class FavouriteXmlReader
    {
        /// <summary>
        /// Reads the supplied xml file and returns a <see cref="IEnumerable{Favourite}"/> containing the favourites in the file.
        /// </summary>
        /// <param name="path">The path to favourites file.</param>
        /// <returns>A <see cref="IEnumerable{Favourite}"/> containing the favourites in the file.</returns>
        public IEnumerable<Favourite> GetFavouritesFromFile(string path)
        {
            if (!File.Exists(path))
            {
                FavouriteXmlWriter writer = new FavouriteXmlWriter();
                writer.CreateNewFavouriteFile(path);
            }
            
            XDocument xml = XDocument.Load(path);
            var favourits = from fav in xml.Descendants("View")
                            select new Favourite
                            {
                                   Name = fav.Value,
                                   X = Convert.ToDouble(fav.Attribute("X").Value,Globals._usNumberFormat),
                                   Y = Convert.ToDouble(fav.Attribute("Y").Value,Globals._usNumberFormat),
                                   Coordsys = fav.Attribute("CoordSys").Value,
                                   Zoom = Convert.ToDouble(fav.Attribute("Zoom").Value, Globals._usNumberFormat),
                                   Units = fav.Attribute("Unit").Value
                            };
            return favourits;
        }
    }
}
